<template>
  <div :class="{ hasTagsViewColMainContent: needTagsView }" class="col-main-content">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <a-card hoverable>
          <a-form ref="queryFormRef" :model="queryParams" layout="inline">
            <a-form-item label="字典名称" name="dictName">
              <a-input v-model:value="queryParams.dictName" allowClear
                       placeholder="请输入" @change="handleQuery" />
            </a-form-item>
            <a-form-item label="字典类型" name="dictType">
              <a-input v-model:value="queryParams.dictType" allowClear
                       placeholder="请输入" @change="handleQuery" />
            </a-form-item>
          </a-form>
        </a-card>
      </div>
    </transition>
    <a-card ref="cardRef" class="card-content" hoverable>
      <template #title>
        <el-row ref="headerRef" :gutter="10">
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:dict:add']" round icon="Plus" plain type="primary" @click="handleAdd">新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:dict:edit']" round :disabled="single" icon="Edit" plain type="success"
                       @click="handleUpdate()">修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:dict:remove']" round plain :disabled="multiple" icon="Delete" type="danger"
                       @click="handleDelete()">
              删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:dict:export']" round icon="Download" plain type="warning" @click="handleExport">
              导出
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:dict:remove']" round plain icon="Refresh" type="info"
                       @click="handleRefreshCache">刷新缓存
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" @query-table="getList"></right-toolbar>
        </el-row>
      </template>
      <a-spin :spinning="loading" size="large">
        <el-table :data="typeList" :height="tableHeight"
                  highlight-current-row @selection-change="handleSelectionChange"
                  @current-change="handleCurrentChange">
          <el-table-column v-if="columns[0].visible" :fixed="columns[0].fixed" align="center" type="selection"
                           min-width="55" />
          <el-table-column v-if="columns[1].visible" :fixed="columns[1].fixed" align="center" label="序号" type="index"
                           min-width="50">
            <template #default="scope">
              <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="columns[2].visible" :fixed="columns[2].fixed" align="center" label="字典编号"
                           min-width="200" prop="dictId" />
          <el-table-column v-if="columns[3].visible" :fixed="columns[3].fixed" :show-overflow-tooltip="true"
                           align="center"
                           label="字典名称"
                           min-width="120"
                           prop="dictName" />
          <el-table-column v-if="columns[4].visible" :fixed="columns[4].fixed" :show-overflow-tooltip="true"
                           align="center"
                           label="字典类型"
                           min-width="200" prop="dictType" />
          <el-table-column v-if="columns[5].visible" :fixed="columns[5].fixed" :show-overflow-tooltip="true"
                           align="center" label="备注"
                           min-width="200" prop="remark" />
          <el-table-column v-if="columns[6].visible" :fixed="columns[6].fixed" align="center" label="创建时间"
                           min-width="180" prop="createTime">
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center"  fixed="right" label="操作"
                           min-width="130">
            <template #default="scope">
              <el-tooltip content="修改" placement="top">
                <el-button v-hasPermi="['system:dict:edit']" circle icon="Edit" plain type="success"
                           @click="handleUpdate(scope.row)"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button v-hasPermi="['system:dict:remove']" circle plain icon="Delete"  type="danger"
                           @click="handleDelete(scope.row)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
          <template #empty>
            <a-empty />
          </template>
        </el-table>
      </a-spin>
    </a-card>
    <a-card hoverable ref="paginationRef" v-show="total>0">
      <pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                  :total="total" @pagination="getList" :pagerCount="5"/>
    </a-card>
    <!-- 添加或修改参数配置对话框 -->
    <el-drawer v-model="drawer.visible" :title="drawer.title" append-to-body size="30%">
      <el-form ref="dictFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="字典名称" prop="dictName">
          <el-input v-model="form.dictName" placeholder="请输入字典名称" />
        </el-form-item>
        <el-form-item label="字典类型" prop="dictType">
          <el-input v-model="form.dictType" placeholder="请输入字典类型" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入内容" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" name="Dict" setup>
import useDictStore from "@/store/modules/dict";
import { addType, delType, getType, listType, refreshCache, updateType } from "@/api/system/dict/type";
import { DictTypeForm, DictTypeQuery, DictTypeVO } from "@/api/system/dict/type/types";

import { useElTableHeight } from "@/utils/useElTableHeight";
import useSettingsStore from "@/store/modules/settings";
import { ReloadOutlined, SearchOutlined } from "@ant-design/icons-vue";

const settingsStore = useSettingsStore();
const needTagsView = computed(() => settingsStore.tagsView);
/*计算表格高度*/
const cardRef = ref<HTMLElement | null>(null);
const headerRef = ref<any>(null);
const paginationRef = ref<any>(null);
const { tableHeight } = useElTableHeight(cardRef, [headerRef, paginationRef]);

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const typeList = ref<DictTypeVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<number | string>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(["", ""]);

const dictFormRef = ref<ElFormInstance>();
const queryFormRef = ref<ElFormInstance>();

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `多选`, visible: true, fixed: true, children: [] },
  { key: 1, label: `序号`, visible: true, fixed: false, children: [] },
  { key: 2, label: `字典编号`, visible: false, fixed: false, children: [] },
  { key: 3, label: `字典名称`, visible: true, fixed: false, children: [] },
  { key: 4, label: `字典类型`, visible: true, fixed: false, children: [] },
  { key: 5, label: `备注`, visible: true, fixed: false, children: [] },
  { key: 6, label: `创建时间`, visible: true, fixed: false, children: [] }
]);

const drawer = reactive<DrawerOption>({
  visible: false,
  title: ""
});

const initFormData: DictTypeForm = {
  dictId: undefined,
  dictName: "",
  dictType: "",
  remark: ""
};
const data = reactive<PageData<DictTypeForm, DictTypeQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    dictName: "",
    dictType: ""
  },
  rules: {
    dictName: [{ required: true, message: "字典名称不能为空", trigger: "blur" }],
    dictType: [{ required: true, message: "字典类型不能为空", trigger: "blur" }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询字典类型列表 */
const getList = () => {
  loading.value = true;
  listType(proxy?.addDateRange(queryParams.value, dateRange.value)).then((res) => {
    typeList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  });
};

/*选中当前行*/
const emit = defineEmits<{
  (e: "getDictType", dictType: string): void;
}>();
const handleCurrentChange = (val: any) => {
  emit("getDictType", val.dictType);
};
/** 取消按钮 */
const cancel = () => {
  reset();
  drawer.visible = false;
};
/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  dictFormRef.value?.resetFields();
};
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ["", ""];
  queryFormRef.value?.resetFields();
  handleQuery();
};
/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  drawer.visible = true;
  drawer.title = "添加字典类型";
};
/** 多选框选中数据 */
const handleSelectionChange = (selection: DictTypeVO[]) => {
  ids.value = selection.map((item) => item.dictId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};
/** 修改按钮操作 */
const handleUpdate = async (row?: DictTypeVO) => {
  reset();
  const dictId = row?.dictId || ids.value[0];
  const res = await getType(dictId);
  Object.assign(form.value, res.data);
  drawer.visible = true;
  drawer.title = "修改字典类型";
};
/** 提交按钮 */
const submitForm = () => {
  dictFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      form.value.dictId ? await updateType(form.value) : await addType(form.value);
      proxy?.$modal.notifySuccess("操作成功");
      drawer.visible = false;
      getList();
    }
  });
};
/** 删除按钮操作 */
const handleDelete = async (row?: DictTypeVO) => {
  const dictIds = row?.dictId || ids.value;
  await proxy?.$modal.confirm("是否确认删除字典编号为\"" + dictIds + "\"的数据项？");
  await delType(dictIds);
  getList();
  proxy?.$modal.notifySuccess("删除成功");
};
/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    "system/dict/type/export",
    {
      ...queryParams.value
    },
    `dict_${new Date().getTime()}.xlsx`
  );
};
/** 刷新缓存按钮操作 */
const handleRefreshCache = async () => {
  await refreshCache();
  proxy?.$modal.notifySuccess("刷新成功");
  useDictStore().cleanDict();
};

onMounted(() => {
  getList();
});
</script>
